'use strict';

const Service = require('egg').Service;

class HomeService extends Service {
  async agree(id) {
    try {
      // 第一步查询出该评论的点赞数量
      const item = await this.app.mysql.select('comment', {
        where: {
          id
        }
      })
      // 第二步是设置该评论的点赞数量
      await this.app.mysql.update('comment', {
        agree: item[0].agree+1
      }, {
        where: {
          id
        }
      })
      return {
        code: 1,
        msg: '点赞成功'
      }
    } catch(e) {
      return {
        code: 0,
        msg: e.message
      }
    }
  }
  async setComment(data) {
    try {
      const res = await this.app.mysql.insert('comment', {
        name: data.name,
        content: data.comment,
        agree: 0,
      })
      console.log(res)
      return {
        code: 1,
        msg: '评论成功'
      }
    } catch(e) {
      return {
        code: 0,
        msg: e.message
      }
    }
  }
  async list() {
    try {
      const res = await this.app.mysql.select('comment')
      return {
        code: 1,
        datas: res
      }
    }catch(e) {
      return {
        code: 0,
        msg: e.message
      }
    }
  }
  async login(data) {
    try {
        const res = await this.app.mysql.select('wyuser', {
            where: {
              name: data.name,
              password: data.password
            }
        })
        if (res.length > 0) { 
          // jwt加密设置cookies
            const token = this.app.jwt.sign({
              name: data.name
            }, this.app.config.jwt.secret, { expiresIn: 5 * 60 * 60 }); // 过期时间设置为5个小时
            this.ctx.cookies.set('token', token)
            console.log('token', token)
            return {
                code: 1,
                msg: '登录成功',
                data: res
            }
        } else {
          return {
            code: 0,
            msg: '登陆失败，该用户不存在'
          }
        }
    } catch(e) {
      return {
          code: 0,
          msg: e.message
      }
    }
  }
}

module.exports = HomeService;
